package com.ruyuan.commodity.consumer.core.consumer.goods;

import com.ruyuan.commodity.model.goods.vo.CacheGoods;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.hutool.json.JSONUtil;
import com.ruyuan.commodity.consumer.api.GoodsFeignClient;
import com.ruyuan.commodity.open.api.client.member.api.MemberCollectGoodsOpenApi;
import com.ruyuan.commodity.open.api.model.base.message.GoodsChangeMsg;
import com.ruyuan.commodity.consumer.core.event.GoodsChangeEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

/**
 * 商品名称变化相关消费
 */
@Service
public class GoodsNameChangeConsumer implements GoodsChangeEvent {

    private static final Logger LOG = LoggerFactory.getLogger(GoodsNameChangeConsumer.class);

    /**
     * 会员收藏商品的open api
     */
    @Autowired
    private MemberCollectGoodsOpenApi memberCollectGoodsOpenApi;

    /**
     * 商品操作的feign client组件
     */
    @Autowired
    private GoodsFeignClient goodsFeignClient;

    @Override
    public void goodsChange(GoodsChangeMsg goodsChangeMsg) {
        LOG.info("进入到商品名称变化的消费逻辑... 入参为 [{}]", JSONUtil.toJsonStr(goodsChangeMsg));

        Long[] goodsIds = goodsChangeMsg.getGoodsIds();
        int operationType = goodsChangeMsg.getOperationType();
        // 更改商品操作 && 商品名称有变化
        if (GoodsChangeMsg.UPDATE_OPERATION == operationType && goodsChangeMsg.isNameChange()) {
            Long goodsId = goodsIds[0];
            CacheGoods goods = goodsFeignClient.getFromCache(goodsId);
            if (ObjectUtils.isEmpty(goods)) {
                return;
            }
            // 更新商品收藏的商品名称
            Boolean flag = memberCollectGoodsOpenApi.updateGoodsName(goods.getGoodsId(), goods.getGoodsName());
            LOG.info("进入到商品名称变化的消费逻辑... flag [{}]", flag);
        }
    }
}
